/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-04
 * Time: 21:33
 */
public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    TreeNode root ;
    public void insert(int val) {
        //当搜索树没有结点时
        if (root == null) {
            root = new TreeNode(val);
            return;
        }

        TreeNode parent = null;
        TreeNode cur = root;
        TreeNode node = new TreeNode(val);
        while (cur != null) {
            if (val > cur.val) {
                parent = cur;
                cur = cur.right;
            }else if (val < cur.val) {
                parent = cur;
                cur = cur.left;
            }else {
                return;
            }
        }
        if (val < parent.val) {
            parent.left = node;
        }else {
            parent.right = node;
        }
    }

    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null) {
            if (key > cur.val) {
                cur = cur.right;
            }else if (key == cur.val) {
                return cur;
            }else {
                cur = cur.left;
            }
        }
        return null;
    }

    public void remove(int key) {
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (key > cur.val) {
                parent = cur;
                cur = cur.right;
            }else if (key < cur.val) {
                parent = cur;
                cur = cur.left;
            }else {
                removeNode(parent,cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
                return;
            }else if (parent.left == cur) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
                return;
            }else if (parent.left == cur) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            TreeNode tp = null;
            TreeNode t = cur.right;
            while (t.left != null) {
                tp = t;
                t = t.left;
            }
            cur.val = t.val;
            if (tp.left == t) {
                tp.left = t.right;
            }else {
                tp.right = t.right;
            }
        }
    }
}
